package com.keyancompany.zhongbaopingtai.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.TextureView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.adapter.ChatMessageAdapter;
import com.keyancompany.zhongbaopingtai.api.CircleAPI;
import com.keyancompany.zhongbaopingtai.api.FriendsAPI;
import com.keyancompany.zhongbaopingtai.api.UserAPI;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.MessageModel;
import com.keyancompany.zhongbaopingtai.utils.IntentUtils;
import com.keyancompany.zhongbaopingtai.utils.T;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by firefox on 2016/6/1.
 */
public class ChatFriendActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    public static String BUNDLE_RES_INFO = "INFOR";
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.bottom_parent)
    LinearLayout bottomParent;
    @Bind(R.id.lv_chart)
    RecyclerView lvChart;
    @Bind(R.id.swipe_layout)
    SwipeRefreshLayout swipeLayout;

    ChatMessageAdapter messageAdapter;
    @Bind(R.id.message_content)
    EditText messageContent;

    private int currentPage = 1, total = 1;
    private List<MessageModel> modelList;
    private String res;
    private String pid;
//    private MessageModel messageModel;

    private String userName;
    private String toUser;
    private String contentValue;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    swipeLayout.setRefreshing(false);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected int getContentViewId() {
        return R.layout.activity_chat_friend;
    }

    @Override
    protected int getMenuId() {
        res = getIntent().getExtras().getString("res");
        if (res.equals(BUNDLE_RES_INFO)) {
            return 0;
        }
        return R.menu.friend_info_menu;
    }

    @Override
    protected void initToolBar() {
        initToolBar(toolbar, userName);
    }

    private void requestMessageAction(int position, MessageModel item, int actionType) {
        String[] params = item.getShotParameter().split(",");
        switch (item.getShotType()) {
            case 1:
                FriendsAPI.addFriendRequest(UserAPI.getUserId(), item.getPID_(),
                        "" + actionType, this, getLoading(R.string.watting_hint));
                break;
            case 2:
                FriendsAPI.teamaddUser(item.getPID_(), params[0], params[1], params[2], "" + actionType,
                        this, getLoading(R.string.watting_hint));
                break;
            case 3:
                FriendsAPI.ouTeam(item.getPID_(), params[0], params[1], params[2], "" + actionType, this, getLoading(R.string.watting_hint));
                break;
            case 4:
                FriendsAPI.rysendMsgRequest(item.getPID_(), params[0], params[1], "" + actionType, this, getLoading(R.string.watting_hint));
                break;
            case 5:
                FriendsAPI.addExperts(item.getPID_(), params[0], "" + actionType, this, getLoading(R.string.watting_hint));
                break;
            case 6:
                FriendsAPI.selectExpert(item.getPID_(), params[0], params[1], "" + actionType, this, getLoading(R.string.watting_hint));
                break;
            case 7:
                CircleAPI.addToCircleRequest(item.getPID_(), "" + actionType, this, getLoading(R.string.watting_hint));
                break;
        }
    }


    @Override
    protected void setUpViews() {

        initSwipeLayout(swipeLayout);
        Bundle bundle = getIntent().getExtras();

        userName = bundle.getString("userName");
//        messageModel = (MessageModel) bundle.getSerializable(Constants.ITEM);
        pid = bundle.getString("pid");
        modelList = new ArrayList<>();
        messageAdapter = new ChatMessageAdapter(modelList);

        messageAdapter.setShotTypeListener(new ChatMessageAdapter.IChateMessageShotTypeListener() {
            @Override
            public void shotTypeClickListener(int position, MessageModel item, int actionType) {
                requestMessageAction(position, item, actionType);
            }
        });
        lvChart.setLayoutManager(new LinearLayoutManager(this));//这里用线性显示 类似于listview
        lvChart.setAdapter(messageAdapter);
        lvChart.smoothScrollToPosition(messageAdapter.getItemCount());

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.friend_info:
                        IntentUtils.startActivity(mContext, SelfPeopleInfoActivity.class);
                        break;
                }
                return false;
            }
        });

        swipeLayout.setOnRefreshListener(this);
        swipeLayout.post(new Thread(new Runnable() {

            @Override
            public void run() {
                swipeLayout.setRefreshing(true);
                onRefresh();
            }
        }));

    }

    @OnClick(R.id.message_send)
    public void toSend(View view) {
        contentValue = messageContent.getText().toString();
        if (TextUtils.isEmpty(contentValue)) return;
        FriendsAPI.sendLetter(contentValue, pid, this, getLoading(R.string.watting_hint));
    }

    public void requestTask() {
        FriendsAPI.getLetterListByPid(2, pid, this, null);
    }

    @Override
    public void success(int type, String json) {
        super.success(type, json);


        BaseModel base = JSONObject.parseObject(json, BaseModel.class);
        if (type == FriendsAPI.LETTER_LIST) {
            modelList.clear();
            mHandler.sendEmptyMessage(1);
            Log.e("MessageFragment", " ---- " + base.toString());
            if (base.isSuccess()) {
                JSONObject object = JSONObject.parseObject(base.data);
                currentPage = object.getInteger(Constants.CURRENT);
                total = object.getInteger(Constants.TOTAL);
                List<MessageModel> list = JSONObject.parseArray(object.getString("list"), MessageModel.class);
                if (messageAdapter == null) return;
                if (total == currentPage) {
                    lvChart.setEnabled(false);
                }
                modelList.addAll(list);
                messageAdapter.notifyDataSetChanged();
                if (list != null && list.size() > 0)
                    lvChart.smoothScrollToPosition(list.size() - 1);
            }
        } else if (type == FriendsAPI.SEND_LETTER) {
            if (base.isSuccess()) {
                messageContent.setText("");
                requestTask();
            }
        } else {
            if (base.isSuccess()) {
                requestTask();
            }
            T.showShort(mContext, base.msg);
        }
    }

    @Override
    public void onRefresh() {
        requestTask();
    }
}
